package com.le.tester.book.effectivejava3rdchinese.articleseventynine;

import com.google.common.collect.ForwardingSet;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;


/**
 * createTime：2022/10/9 13:48
 * description：观察者模式，不要过度的同步代码
 */
public class ObservableSet<E> extends ForwardingSet<E> {

    private final List<SetObserver<E>> observers = new ArrayList<>();



    private final List<SetObserver<E>> observerList = new CopyOnWriteArrayList<>();
    //以下是疯狂使用同步锁得例子
    //并不建议使用

    public void addObserver(SetObserver<E> observer) {
        //这边添加同步锁应该是不变的变量
        synchronized (observers) {
//            synchronized (observer) {
            observers.add(observer);
        }
    }

    public Boolean removeObserver(SetObserver<E> observer) {
        synchronized (observers) {
            return observers.remove(observer);
        }

    }

    public void notifyElementAdded(E element) {
        synchronized (observers) {
            for (SetObserver<E> observer : observers) {
                observer.added(this, element);
            }
        }
    }

    @Override
    protected Set<E> delegate() {
        return null;
    }

    @Override
    public boolean add(E element) {
        boolean added = super.add(element);
        if (added) {
            notifyElementAdded(element);
        }
        return added;
    }

    @Override
    public boolean addAll(Collection<? extends E> collection) {
        boolean result = false;
        for (E element : collection)
            //二进制或运行，有1则得1
            //&二进制且运算，两者值相同则为1
            //&=
            result |= add(element);
        return result;
    }

    //    public ObservableSet(Set<E> set) {
//        super(set);
//    }

    public static void main(String[] args) {
//        int a = 6, b = 5;
//        a |= b;
//        System.out.println(a);
        ObservableSet<Integer> set = new ObservableSet<>();
        set.addObserver((s, e) -> System.out.println(e));
        for (int i = 0; i < 100; i++) {
            set.add(i);
        }
    }
}
